package com.heima.wemedia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.heima.apis.article.IArticleClient;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.CheckNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.dtos.wmNewsListDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsPageVO;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author itlxc
 * @since 2024-07-26
 */
@Service
@Slf4j
@Transactional
@RequiredArgsConstructor
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    private final WmNewsMaterialMapper wmNewsMaterialMapper;

    private final WmMaterialMapper wmMaterialMapper;

    private final WmNewsAutoScanService wmNewsAutoScanService;

    private final WmNewsMapper wmNewsMapper;

    @Autowired
    private  KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        // 1.检查参数
        if (ObjectUtil.isNull(dto)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数检查
        dto.checkParam();
        //获取当前登录人的信息
        WmUser user = WmThreadLocalUtil.getUser();
        if (ObjectUtil.isNull(user)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2.分页条件查询
        Page<WmNews> page = this.lambdaQuery()
                .eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus())
                .eq(WmNews::getUserId, user.getId())
                .like(StrUtil.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword())
                .eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId())
                .between(dto.getBeginPubDate() != null && dto.getEndPubDate() != null,
                        WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate())
                .orderByDesc(WmNews::getCreatedTime)
                .page(new Page<>(dto.getPage(), dto.getSize()));
        // 3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(),
                (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 发布文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        // 1.检查参数
        if (ObjectUtil.isNull(dto) || StrUtil.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2.封装WmNews对象
        WmNews wmNews = BeanUtil.copyProperties(dto, WmNews.class);
        // 2.1封面图片用逗号分隔
        if (CollUtil.isNotEmpty(dto.getImages())) {
            wmNews.setImages(CollUtil.join(dto.getImages(), ","));
        }
        // 2.2如果当前封面类型为自动，type为null
        if (ObjectUtil.equal(dto.getType(), WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1); // 默认上架
        // 2.3保存或修改文章
        saveOrUpdateWmNews(wmNews);
        // 3.判断是否为草稿  如果为草稿结束当前方法
        if (ObjectUtil.equal(dto.getStatus(), WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        // 4.提取文章内容中的图片信息
        List<String> materials = ectractUrlInfo(dto.getContent());
        // 5.不是草稿，保存文章内容图片与素材的关系
        saveRelativeInfoForContent(materials, wmNews.getId());
        // 6.不是草稿，保存文章封面图片与素材的关系，如果当前布局是自动，需要匹配封面图片
        saveRelativeInfoForCover(dto, wmNews, materials);
        // 7.审核文章
        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 第一个功能：如果当前封面类型为自动，则设置封面类型的数据
     * 匹配规则：
     * 1，如果内容图片大于等于1，小于3  单图  type 1
     * 2，如果内容图片大于等于3  多图  type 3
     * 3，如果内容没有图片，无图  type 0
     * 第二个功能：保存封面图片与素材的关系
     *
     * @param dto
     * @param wmNews
     * @param materials
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        List<String> images = dto.getImages();
        // 第一个功能：如果当前封面类型为自动，则设置封面类型的数据
        if (ObjectUtil.equal(dto.getType(), WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            // 1，如果内容图片大于等于1，小于3  单图  type 1
            if (materials.size() >= 1 && materials.size() < 3) {
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            } else if (materials.size() >= 3) {
                // 2，如果内容图片大于等于3  多图  type 3
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            } else {
                // 3，如果内容没有图片，无图  type 0
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            if (CollUtil.isNotEmpty(images)) {
                wmNews.setImages(CollUtil.join(images, ","));
            }
            this.updateById(wmNews);
        }
        // 第二个功能：保存封面图片与素材的关系
        if (CollUtil.isNotEmpty(images)) {
            saveRelativeInfoForContent(images, wmNews.getId());
        }
    }

    /**
     * 保存文章与素材的关系
     *
     * @param materials
     * @param id
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer id) {
        if (CollUtil.isEmpty(materials)) {
            return;
        }
        List<WmMaterial> materialList = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));
        if (CollUtil.isEmpty(materialList)) {
            throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
        }
        if (materials.size() != materialList.size()) {
            throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
        }
        List<Integer> ids = materialList.stream()
                                        .map(WmMaterial::getId)
                                        .collect(Collectors.toList());
        wmNewsMaterialMapper.saveRelations(ids, id, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 提取文章内容中的图片信息
     *
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<Map> list = JSONUtil.toList(content, Map.class);
//        List<Map> list = JSON.parseArray(content, Map.class);
        /*list.forEach(item -> {
            if (ObjectUtil.equal(item.get("type"), "image")) {
                urls.add(item.get("value").toString());
            }
        });
        return urls;*/
        return list.stream().filter(map -> ObjectUtil.equal(map.get("type"), "image"))
                    .map(map -> (String) map.get("value"))
                    .collect(Collectors.toList());
    }


    /**
     * 保存或修改文章
     *
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        // 保存
        if (ObjectUtil.isNull(wmNews.getId())) {
            this.save(wmNews);
            return;
        }
        // 修改并且删除文章图片与素材的关系
        this.updateById(wmNews);
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
    }

    /**
     * 自媒体文章上下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        // 1.检查参数
        if (ObjectUtil.isNull(dto)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章id不可缺少");
        }
        // 2.检查文章是否存在
        WmNews wmNews = getById(dto.getId());
        if (ObjectUtil.isNull(wmNews)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        // 3.检查文章是否已经发布并且是上架或下架
        if (ObjectUtil.notEqual(wmNews.getStatus(), WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章不是发布状态不能上下架");
        }
        if (ObjectUtil.isNotNull(dto.getEnable()) &&  dto.getEnable() > -1 && dto.getEnable() < 2) {
        // 4.修改文章上下架状态
            wmNews.setEnable(dto.getEnable());
            this.updateById(wmNews);
        }
        // 5.发送消息，通知article服务修改文章配置
        if (ObjectUtil.isNotNull(wmNews.getArticleId())) {
            Map<String, Object> msg = new HashMap<>(2);
            msg.put("articleId", wmNews.getArticleId());
            msg.put("enable", dto.getEnable());
            log.info("发送消息：{}", msg);
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSONUtil.toJsonStr(msg));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private IArticleClient iArticleClient;

    /**
     * 查询文章列表
     * @param wmNewsListDTO
     * @return
     */
    @Override
    public ResponseResult wmNewsList(wmNewsListDTO wmNewsListDTO) {
        PageHelper.startPage(wmNewsListDTO.getPage(), wmNewsListDTO.getSize());
        com.github.pagehelper.Page<WmNewsPageVO> page = wmNewsMapper.pageQuery(wmNewsListDTO);
        PageResponseResult result = new PageResponseResult(wmNewsListDTO.getPage(), wmNewsListDTO.getSize(), (int) page.getTotal());
        result.setData(page.getResult());
        return result;
    }

    @Override
    public ResponseResult checkAuthFail(CheckNewsDTO dto) {
        WmNews wmNews = new WmNews();
        wmNews.setId(dto.getId());
        wmNews.setReason(dto.getMsg());
        wmNews.setStatus(WmNews.Status.FAIL.getCode());
        this.updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult checkAuthPass(CheckNewsDTO dto) {
        WmNews wmNews = new WmNews();
        wmNews.setId(dto.getId());
        wmNews.setStatus(WmNews.Status.ADMIN_SUCCESS.getCode());
        this.updateById(wmNews);
        WmNews news = this.getById(dto.getId());
        // 发起远程调用文章服务
        if (ObjectUtil.isNotNull(news)) {
            ArticleDto articleDto = BeanUtil.copyProperties(news, ArticleDto.class, "id");
            articleDto.setLayout(news.getType());
            ResponseResult result = iArticleClient.saveArticle(articleDto);
            if (result.getCode() == AppHttpCodeEnum.SUCCESS.getCode()) {
                wmNews.setArticleId(Long.valueOf(result.getData().toString()));
                this.updateById(wmNews);
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            }
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
}



